package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.api.domin.ProductSku;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-04-28
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;
    @Override
    public List<Product> getlist() {
        List<Product> list =productMapper.getall();
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveProduct(Product product) {
        //1.新增商品SPU信息
        //1.1 设置商品初始状态：0：未上架
        product.setStatus(0);
        //1.2 设置商品创建人
        product.setCreateBy(SecurityUtils.getUsername());
        //1.3保存spu信息
        baseMapper.insert(product);
        //1.4获取商品id
        Long productId = product.getId();

        //2增加商品详细信息
        //2.1构建商品详细对象
        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(productId);
        productDetails.setCreateBy(SecurityUtils.getUsername());
        //为图片列表赋值
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        if (!ObjectUtils.isEmpty(detailsImageUrlList)){
            //将多个字符串（或字符串集合）用指定的 分隔符 连接成一个新的字符串。
            String string = String.join(",", detailsImageUrlList);
            productDetails.setImageUrls(string);
        }
        //将商品详细信息保存
        productDetailsMapper.insert(productDetails);

        //3增加sku表信息
        //3.1先获取到前端发来的sku信息
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (!ObjectUtils.isEmpty(productSkuList)){
            int num =1;
            for (ProductSku productSku : productSkuList) {
                //生成sku商品编号
                productSku.setSkuCode(productId+"-"+num++);
                //生成sku名称,规则,商品,名称,规格参数
                productSku.setSkuName(product.getName()+" "+productSku.getSkuSpec());
                //加入spu的id
                productSku.setProductId(productId);
                //设置初始状态
                productSku.setStatus(0);
                //设置创建人
                productSku.setCreateBy(SecurityUtils.getUsername());
                //保存sku信息
                productSkuMapper.insert(productSku);

                //保存sku库存信息
                Long skuId = productSku.getId();
                SkuStock skuStock = new SkuStock();
                skuStock.setSkuId(skuId);
                skuStock.setStatus(0);
                skuStock.setTotalNum(productSku.getStockNum());
                skuStock.setAvailableNum(productSku.getStockNum());
                skuStock.setLockNum(0);
                skuStock.setSaleNum(0);
                skuStock.setCreateBy(SecurityUtils.getUsername());
                skuStockMapper.insert(skuStock);
            }
        }
    }
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long spuId, Integer status) {
       //修改spu状态
        Product product = new Product();
        product.setId(spuId);
        product.setStatus(status);
        product.setUpdateBy(SecurityUtils.getUsername());
        baseMapper.updateById(product);

        //修改sku状态
        LambdaUpdateWrapper<ProductSku> productSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        productSkuLambdaUpdateWrapper.eq(ProductSku::getProductId,spuId);
        productSkuLambdaUpdateWrapper.set(ProductSku::getStatus,status);
        productSkuMapper.update(null,productSkuLambdaUpdateWrapper);
        //方法二
       /* ProductSku productSku = new ProductSku();
        productSku.setStatus(status);
        productSku.setCreateBy(SecurityUtils.getUsername());
        LambdaUpdateWrapper<ProductSku> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProductSku::getProductId,spuId);
        productSkuMapper.update(productSku,updateWrapper);*/

        //修改库存状态
        //先获取skuid
        LambdaQueryWrapper<ProductSku> productSkuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productSkuLambdaQueryWrapper.eq(ProductSku::getProductId,spuId);
        productSkuLambdaQueryWrapper.select(ProductSku::getId);
        List<ProductSku> productSkus = productSkuMapper.selectList(productSkuLambdaQueryWrapper);
        List<Long> skuIdList = productSkus.stream().map(ProductSku::getId).collect(Collectors.toList());
        //根据skuid修改库存的状态
        LambdaUpdateWrapper<SkuStock> skuStockLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        skuStockLambdaUpdateWrapper.in(SkuStock::getSkuId,skuIdList);
        skuStockLambdaUpdateWrapper.set(SkuStock::getStatus,status);
        skuStockMapper.update(null,skuStockLambdaUpdateWrapper);
        //判断上下架状态将商品加入reids-bitmap
        skuIdList.forEach(skuId->{
            if (status==1){
                redisTemplate.opsForValue().setBit("product:sku:data",skuId,true);
            }else if (status==-1){
                redisTemplate.opsForValue().setBit("product:sku:data",skuId,false);
            }
        });

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeProduct(List<Long> ids) {
        //1.删除商品SPU表
        baseMapper.deleteBatchIds(ids);

        //2.根据商品SPUID查询SKUID列表
        List<ProductSku> productSkuList = productSkuMapper.selectList(
                new LambdaQueryWrapper<ProductSku>()
                        .in(ProductSku::getProductId, ids)
                        .select(ProductSku::getId)
        );
        if (!CollectionUtils.isEmpty(productSkuList)) {
            List<Long> skuIdList = productSkuList
                    .stream()
                    .map(ProductSku::getId)
                    .collect(Collectors.toList());
            //3.删除商品SKU表
            productSkuMapper.deleteBatchIds(skuIdList);
            //4.删除商品SKU库存表
            skuStockMapper.delete(
                    new LambdaQueryWrapper<SkuStock>()
                            .in(SkuStock::getSkuId, skuIdList)
            );
        }
        //5.删除商品SPU详情表
        productDetailsMapper.delete(
                new LambdaQueryWrapper<ProductDetails>()
                        .in(ProductDetails::getProductId, ids)
        );
    }
}
